﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Protocol;

namespace Smart.Model
{
    public partial class NetMessageDecoder : IMessageDecoder
    {
        Dictionary<ushort, System.Func<Google.Protobuf.IMessage>> mMsgDic = new Dictionary<ushort, System.Func<Google.Protobuf.IMessage>>(128);

        System.Func<Google.Protobuf.IMessage> GetFactory<T>() where T : class,Google.Protobuf.IMessage
        {
            return () => { return MessagePool.Instance.Fetch(typeof(T)) as T; };
        }

        void AddFactory<T>(ushort msgId) where T : class, Google.Protobuf.IMessage
        {
            if (!mMsgDic.ContainsKey(msgId))
                mMsgDic.Add(msgId,GetFactory<T>());
        }

        public NetMessageDecoder()
        {
            Register();
        }

        public object GetDecoder(ushort opcode)
        {
            if (mMsgDic.TryGetValue(opcode, out System.Func<Google.Protobuf.IMessage> functor))
                return functor();
            return null;
        }
    }
}